﻿using Unity.Entities;
using UnityEngine.InputSystem;

[UpdateBefore(typeof(MovementSystem))]
public class PlayerInputSystem : ComponentSystem
{
    private EntityQuery entityQuery;

    protected override void OnCreate()
    {
        entityQuery = GetEntityQuery(typeof(PlayerInputData));
    }

    protected override void OnUpdate()
    {
        float moveX = 0;
        float moveY = 0;
        var keyboard = Keyboard.current;
        if (keyboard != null)
        {
            // left
            if (keyboard.leftArrowKey.isPressed || keyboard.aKey.isPressed)
            {
                moveX = -1;
            }
            // right
            if (keyboard.rightArrowKey.isPressed || keyboard.dKey.isPressed)
            {
                moveX = 1;
            }
            // up
            if (keyboard.upArrowKey.isPressed || keyboard.wKey.isPressed)
            {
                moveY = 1;
            }
            // down
            if (keyboard.downArrowKey.isPressed || keyboard.sKey.isPressed)
            {
                moveY = -1;
            }
        }

        if (entityQuery.CalculateEntityCount() != 0)
        {
            var inputData = new PlayerInputData()
            {
                MoveX = moveX,
                MoveY = moveY
            };
            entityQuery.SetSingleton<PlayerInputData>(inputData);
        }
    }
}